package com.ty.common.core.common.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 自定义线程池配置
 * @Author: TangYuan
 * @Date: 2025/8/13 11:07
 */
@EnableAsync
@Configuration
public class ThreadTaskConfiguration {

    private static final String THREAD_NAME_PREFIX = "admin-x-thread_";

    @Bean
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 核心线程数5个
        executor.setCorePoolSize(5);
        // 最大线程数30个
        executor.setMaxPoolSize(30);
        // 任务队列最大容量200
        executor.setQueueCapacity(200);
        // 空闲线程存活时间60秒
        executor.setKeepAliveSeconds(60);
        // 线程名称前缀
        executor.setThreadNamePrefix(THREAD_NAME_PREFIX);
        // 拒绝策略：由调用线程处理该任务
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 关闭时等待任务完成
        executor.setWaitForTasksToCompleteOnShutdown(true);
        // 等待终止时间60秒
        executor.setAwaitTerminationSeconds(60);
        return executor;
    }
}